package com.meevle.commands {
	
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.meevle.business.UserDelegate;
	import com.meevle.error.ErrorHandler;
	import com.meevle.events.LoginEvent;
	import com.meevle.model.ViewModelLocator;
	import com.meevle.vo.LoginVO;
	
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	
	public class LoginCommand implements ICommand, IResponder {
	
		private var loginAttempt:LoginVO;
		
		public function LoginCommand() {
			
		}
		
		// ICommand interface method
		public function execute(event:CairngormEvent):void {
			ViewModelLocator.getInstance().loginStatus = ViewModelLocator.LOGGING_IN;
			
			var loginEvent:LoginEvent = event as LoginEvent;
			loginAttempt = loginEvent.loginAttempt;
			
			var delegate:UserDelegate = new UserDelegate(this);
			delegate.login( loginAttempt );
		}
		
		//IResponder interface methods
		public function result(event:Object) : void {
			if(event.result == true) {
				// LOGIN SUCCESS
				ViewModelLocator.getInstance().loginError = null;
				ViewModelLocator.getInstance().login = loginAttempt;
				ViewModelLocator.getInstance().loginStatus = ViewModelLocator.LOGGED_IN;
				ViewModelLocator.getInstance().isLoggedIn = true;			
			} else {
				// LOGIN ERROR
				var error:Error = new Error("Wrong username and/or password combination"); 
				ViewModelLocator.getInstance().loginError = error;
				ViewModelLocator.getInstance().loginStatus = ViewModelLocator.NOT_LOGGED_IN;
				ViewModelLocator.getInstance().isLoggedIn = false;
			}
			ViewModelLocator.getInstance().error = null;
		}
		
		public function fault(event:Object) : void {
			ErrorHandler.getInstance().handleError(event as FaultEvent);
		}	
	}
}